#! /bin/bash
TIME=$(date "+%Y%m%d%H%M%S")
read -p "enter server ip:" HOST
read -p "passwd of pem:" PWD
# install docker
if ! [ -x "$(command -v docker)" ]; then
  echo 'Error: docker is not installed.' >&2
  curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
fi
# Generate pem
cd /etc/docker
openssl genrsa -aes256 -passout pass:$PWD  -out ca-key.pem 4096 
openssl req -new -x509 -days 365 -key ca-key.pem -sha256  -passin pass:$PWD -out ca.pem  -subj /C=CN/ST=CN/O=Internet/CN=$HOST
openssl genrsa -out server-key.pem 4096
openssl req -subj "/CN=$HOST" -sha256 -new -key server-key.pem -out server.csr
echo subjectAltName = DNS:$HOST,IP:$HOST >> extfile.cnf
echo extendedKeyUsage = serverAuth >> extfile.cnf
openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem -passin pass:$PWD -CAcreateserial -out server-cert.pem -extfile extfile.cnf
openssl genrsa -out key.pem 4096
openssl req -subj '/CN=client' -new -key key.pem -out client.csr
echo extendedKeyUsage = clientAuth > extfile-client.cnf
openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -passin pass:$PWD -CAcreateserial -out cert.pem -extfile extfile-client.cnf
chmod -v 0400 ca-key.pem key.pem server-key.pem
chmod -v 0444 ca.pem server-cert.pem cert.pem
if [ -e /etc/docker/daemon.json ]; then
	echo "daemon.json exist.backup to deamon.json.$TIME"
	mv /etc/docker/daemon.json /etc/docker/daemon.json.$TIME
fi
# setting docker
echo -e "{\n \"tlsverify\":true,\n \"tlscacert\":\"/etc/docker/ca.pem\",\n \"tlscert\":\"/etc/docker/server-cert.pem\",\n \"tlskey\":\"/etc/docker/server-key.pem\"\n}" > /etc/docker/daemon.json
STARTSH=`cat /usr/lib/systemd/system/docker.service | grep -w ExecStart`
STARTSH_AFTER="ExecStart=/usr/bin/dockerd  -H tcp://$HOST:2376 -H unix://var/run/docker.sock  --containerd=/run/containerd/containerd.sock"
if [ -n "$STARTSH" ]; then
	cp /usr/lib/systemd/system/docker.service /usr/lib/systemd/system/docker.service.$TIME
	echo "change $STARTSH to $STARTSH_AFTER, the original file is backup to /usr/lib/systemd/system/docker.service.$TIME"
	sed -i "s!$STARTSH!$STARTSH_AFTER!g" /usr/lib/systemd/system/docker.service
fi
# setting firewalld
if systemctl is-active firewalld &>/dev/null ;then
	echo "firewalld is active!"
else
	echo "start firewalld"
	systemctl start firewalld
fi
## 将2376加入允许的端口列表
firewall-cmd --zone=public --add-port=2376/tcp --permanent
firewall-cmd --reload
## 查看是否加入成功
firewall-cmd --zone=public --query-port=2376/tcp
systemctl daemon-reload
systemctl restart docker
if systemctl is-active docker &>/dev/null ;then
	echo "###################################################################################"
	echo "## Generating success! please download ca.pem cert.pem key.pem from /etc/docker/ ##"
	echo "###################################################################################"
else
	echo "failed!"
	systemctl status docker
fi